<script>
import UploadList from './upload-list';
import Upload from './upload';
import ElProgress from 'element-ui/packages/progress';
import Migrating from 'element-ui/src/mixins/migrating';

function noop() {}

export default {
    name: 'ElUpload',

    mixins: [Migrating],

    components: {
        ElProgress,
        UploadList,
        Upload
    },

    provide() {
        return {
            uploader: this
        };
    },

    inject: {
        elForm: {
            default: ''
        }
    },

    props: {
        action: {
            type: String,
            required: true
        },
        headers: {
            type: Object,
            default () {
                return {};
            }
        },
        data: Object,
        multiple: Boolean,
        name: {
            type: String,
            default: 'file'
        },
        drag: Boolean,
        dragger: Boolean,
        withCredentials: Boolean,
        showFileList: {
            type: Boolean,
            default: true
        },
        accept: String,
        type: {
            type: String,
            default: 'select'
        },
        beforeUpload: Function,
        beforeRemove: Function,
        onRemove: {
            type: Function,
            default: noop
        },
        onChange: {
            type: Function,
            default: noop
        },
        onPreview: {
            type: Function
        },
        onSuccess: {
            type: Function,
            default: noop
        },
        onProgress: {
            type: Function,
            default: noop
        },
        onError: {
            type: Function,
            default: noop
        },
        fileList: {
            type: Array,
            default () {
                return [];
            }
        },
        autoUpload: {
            type: Boolean,
            default: true
        },
        listType: {
            type: String,
            default: 'text' // text,picture,picture-card
        },
        httpRequest: Function,
        disabled: Boolean,
        limit: Number,
        onExceed: {
            type: Function,
            default: noop
        }
    },

    data() {
        return {

            dragOver: false,
            draging: false,
            tempIndex: 1,

            uploadFolders: [],

            //并发上传文件夹个数
            maxConcurentUplaods: 5,

            //uploadingFoldersIndex: 0,

            uploadingFolderNums: 0

        };
    },
    destroyed() {
        this.uploadFolders = [];
    },
    computed: {
        uploadDisabled() {
            return this.disabled || (this.elForm || {}).disabled;
        }
    },

    watch: {
        
    },

    methods: {

        startUpload(){

            let folderArray = this.uploadFolders;

            //导入队列后， 需要补充上传的数量
            var needUpload = this.maxConcurentUplaods - this.uploadingFolderNums;

            if (needUpload > 0) {

                // 从哪个位置开始
                var startIndexOffset = this.uploadingFolderNums + 0;

                // 遍历文件夹数组
                for (var i = startIndexOffset, tmpLen = folderArray.length; i < tmpLen; i++) {

                    var tmpArrayObj = folderArray[i];

                    if(tmpArrayObj.status != 'init'){
                        continue;
                    }

                    var tmpFile = tmpArrayObj.fileArray[0];

                    tmpArrayObj.uploadingName = tmpFile.name;

                    tmpArrayObj.status = 'uploading';

                    this.$refs['upload-inner'].upload(tmpFile, tmpArrayObj.folderName);

                    this.uploadingFolderNums++;

                    if(this.uploadingFolderNums >= this.maxConcurentUplaods){
                        break;
                    }
                }
            }
        },

        handleStart(uploadFolders) {
         
            for (var i = 0; i < uploadFolders.length; i++) {
                this.uploadFolders.push(uploadFolders[i]);
            }

            this.startUpload();
        },

        //根据 file uuid 查找文件夹
        getRecord(fileUID) {

            let fileList = this.uploadFolders;
            let target;
            let folderId = fileUID.substring(0, fileUID.indexOf('_'));

            for (var i = 0; i < fileList.length; i++) {
                if (fileList[i].uid == folderId) {
                    return fileList[i];
                }
            }
            return target;

        },
        handleProgress(ev, rawFile) {

            const folder = this.getRecord(rawFile.uid);
            if (folder) {
                folder.percentage = ev.percent || 0;
            }

        },
        handleSuccess(res, rawFile) {

            const folder = this.getRecord(rawFile.uid);

            if (folder) {

                folder.successNums = folder.successNums + 1;

                //该文件夹还有文件没有上传
                if (folder.successNums < folder.fileNums) {
                    folder.percentage = 0;

                    var nextFile = folder.fileArray[folder.successNums];
                    folder.uploadingName = nextFile.name;
                    folder.status = 'uploading';
                    this.$refs['upload-inner'].upload(nextFile,folder.folderName);

                }
                //文件夹下的文件 全部上传完毕
                else {

                    folder.status = 'success';
                    folder.uploadingName = '上传完成';

                    //当前正在上传的数量 -1
                    this.uploadingFolderNums--;

                    //继续上传其他文件夹
                    this.startUpload();
                    let folderArray = this.uploadFolders;
                    
                    //上传成功后 从队列中删除
                    window.setTimeout(function() {
                        for (var i = 0; i < folderArray.length; i++) {
                            if (folderArray[i].uid == folder.uid) {
                                folderArray.splice(i, 1);
                                break;
                            }
                        }
                    }, 3000);               


                    this.onSuccess(folder);
                }
            }
            
        },
        handleError(err, rawFile) {

            const folder = this.getRecord(rawFile.uid);

            this.$message({
                showClose: true,
                message: '证据包:[' + folder.folderName + ']上传失败，请稍后再试',
                type: 'error'
            });

            this.handleRemove(folder);
        },
        handleRemove(tmpFolder) {

            const folderArray = this.uploadFolders;

            var targetFolder;
            for (var i = 0; i < folderArray.length; i++) {
                if (folderArray[i].uid == tmpFolder.uid) {
                    targetFolder = folderArray.splice(i, 1)[0];
                    break;
                }
            }

            if (!targetFolder) {
                return;
            }

            // 如果被删除的文件夹状态是上传中
            if (targetFolder.status && targetFolder.status == 'uploading') {

                this.uploadingFolderNums--;

                //remove 掉一个任务， 后续任务要跟 上
                this.startUpload();                
            }
        },

        clearFiles() {
            this.uploadFiles = [];       
        },

        getMigratingConfig() {
            return {
                props: {
                    'default-file-list': 'default-file-list is renamed to file-list.',
                    'show-upload-list': 'show-upload-list is renamed to show-file-list.',
                    'thumbnail-mode': 'thumbnail-mode has been deprecated, you can implement the same effect according to this case: http://element.eleme.io/#/zh-CN/component/upload#yong-hu-tou-xiang-shang-chuan'
                }
            };
        }
    },

    beforeDestroy() {
        // this.uploadFiles.forEach(file => {
        //     if (file.url && file.url.indexOf('blob:') === 0) {
        //         URL.revokeObjectURL(file.url);
        //     }
        // });
    },

    render(h) {
        let uploadList;

        if (this.showFileList) {
            uploadList = (
                <UploadList
          disabled={this.uploadDisabled}
          listType={this.listType}
          files={this.uploadFolders}
          on-remove={this.handleRemove}
          handlePreview={this.onPreview}
          >
        </UploadList>
            );
        }

        const uploadData = {
            props: {
                type: this.type,
                drag: this.drag,
                action: this.action,
                multiple: this.multiple,
                'before-upload': this.beforeUpload,
                'with-credentials': this.withCredentials,
                headers: this.headers,
                name: this.name,
                data: this.data,
                accept: this.accept,
                fileList: this.uploadFiles,
                autoUpload: this.autoUpload,
                listType: this.listType,
                disabled: this.uploadDisabled,
                limit: this.limit,
                'on-exceed': this.onExceed,
                'on-start': this.handleStart,
                'on-progress': this.handleProgress,
                'on-success': this.handleSuccess,
                'on-error': this.handleError,
                'on-preview': this.onPreview,
                'on-remove': this.handleRemove,
                'http-request': this.httpRequest
            },
            ref: 'upload-inner'
        };

        const trigger = this.$slots.trigger || this.$slots.default;
        const uploadComponent = <upload {...uploadData}>{trigger}</upload>;

        return (
            <div>
        { this.listType === 'picture-card' ? uploadList : ''}
        {
          this.$slots.trigger
            ? [uploadComponent, this.$slots.default]
            : uploadComponent
        }
        {this.$slots.tip}
        { this.listType !== 'picture-card' ? uploadList : ''}
      </div>
        );
    }
};

</script>
